<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Models\CodePlace;
use App\Validate\CodePlaceValidate;
use Illuminate\Support\Facades\DB;

/**
 * 码上借系统
 */
class CodePlaceController extends CommonController
{

    private $validate = null;
    private $model = null;
    public function __construct()
    {
        parent::__construct();
        $this->model = new CodePlace();
        $this->validate = new CodePlaceValidate();
    }

    /**
     * 筛选列表(用于下拉框选择)
     */
    public function filterList()
    {

        $condition[] = ['is_del', '=', 1];
        return $this->model->getFilterList(['id', 'name'], $condition);
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 开始时间(开始)
     * @param end_time datetime 开始时间(截止)
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $is_play = request()->is_play;
        $keywords = request()->keywords;
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        $res = $this->model->lists($keywords, $start_time, $end_time, $is_play, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            $res['data'][$key]['distance'] = $val['distance'] ? $val['distance'] : config('other.distance');
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 比赛id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }
        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 添加场所码
     * @param name 名称
     * @param way  定位方式  1 经纬度   2 地址
     * @param lon 经度
     * @param lat 纬度
     * @param province 纬度
     * @param city 市
     * @param district 区、县
     * @param address 详细地址
     * @param intro 备注
     * @param distance 距离，单位米，只有admin才显示，其余不显示，也不允许修改
     */
    public function add()
    {
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $is_exists = $this->model->nameIsExists($this->request->name, 'name');
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }
        /*生成经纬度*/
        $data = $this->request->all();
        if ($this->request->way == 1) {
            if (empty($this->request->lon) || empty($this->request->lat)) {
                return $this->returnApi(202, "经纬度不能为空");
            }

            $map = $this->getAddressByLonLat($this->request->lon, $this->request->lat);
            if (is_string($map)) return $this->returnApi(202, $map);
            $data['province']      = $map['province'];
            $data['city']          = !empty($map['city']) ? $map['city'] : $map['province'];
            $data['district']        = $map['district'];
            $data['address']       = $map['remark'];
        } else {
            if (empty($this->request->province) || empty($this->request->city) || empty($this->request->district) && !empty($this->request->address)) {
                return $this->returnApi(202, "省市区地址信息不能为空");
            }
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                return $this->returnApi(202, $map);
            }
            $data['lon']      = $map['lon'];
            $data['lat']          = $map['lat'];
        }

        if ($this->request->manage_id != 1) {
            unset($data['distance']); //不是admin，不允许配置距离信息
        }

        $qrCodeObj = new QrCodeController();
        $qr_code = $qrCodeObj->getQrCode('code_place');
        if ($qr_code === false) {
            return $this->returnApi(201, "添加失败，请重新添加");
        }
        //生成二维码
        $qr_url = $qrCodeObj->setQr($qr_code, true, 300, 1, [0, 0, 0]);

        DB::beginTransaction();
        try {
            $data['qr_code'] = $qr_code;
            $data['qr_url'] = $qr_url;
            $this->model->add($data);

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    /**
     * 编辑
     * @param id int id
     * @param name 名称
     * @param way  定位方式  1 经纬度   2 地址
     * @param lon 经度
     * @param lat 纬度
     * @param province 纬度
     * @param city 市
     * @param district 区、县
     * @param address 详细地址
     * @param intro 备注
     * @param distance 距离，单位米，只有admin才显示，其余不显示，也不允许修改
     */
    public function change()
    {
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }
        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        /*生成经纬度*/
        $data = $this->request->all();
        if ($this->request->way == 1) {
            if (empty($this->request->lon) || empty($this->request->lat)) {
                return $this->returnApi(202, "经纬度不能为空");
            }

            if ($res->lon != $this->request->lon || $res->lat != $this->request->lat) {
                $map = $this->getAddressByLonLat($this->request->lon, $this->request->lat);
                if (is_string($map)) return $this->returnApi(202, $map);
                $data['province']      = $map['province'];
                $data['city']          = !empty($map['city']) ? $map['city'] : $map['province'];
                $data['district']        = $map['district'];
                $data['address']       = $map['remark'];
            }
        } else {
            if (empty($this->request->province) || empty($this->request->city) || empty($this->request->district) && !empty($this->request->address)) {
                return $this->returnApi(202, "省市区地址信息不能为空");
            }
            if ($res->province != $this->request->province || $res->city != $this->request->city || $res->district != $this->request->district || $res->address != $this->request->address) {
                $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
                if (is_string($map)) {
                    return $this->returnApi(202, $map);
                }
                $data['lon']      = $map['lon'];
                $data['lat']      = $map['lat'];
            }
        }

        if ($this->request->manage_id != 1) {
            unset($data['distance']); //不是admin，不允许配置距离信息
        }

        DB::beginTransaction();
        try {
            $this->model->change($data);
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除
     * @param id int 比赛id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }




    /**
     * 发布与取消发布
     * @param ids 场所码id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }
}
